# app.py - 完整修复版
import requests
from flask import Flask, request, jsonify
from flask_cors import CORS
from datetime import datetime, timedelta
import json
import os
import traceback

from config import Config
from food_analysis import FoodAnalysis

app = Flask(__name__)
app.config.from_object(Config)

# 初始化扩展
CORS(app)

# 食物分析实例
food_analyzer = FoodAnalysis()

# 模拟数据存储
food_records = []
food_database = [
    {'id': 1, 'name': '白米饭', 'category': '主食', 'calories': 130, 'protein': 2.6, 'carbs': 28.2, 'fat': 0.3,
     'fiber': 0.4},
    {'id': 2, 'name': '鸡胸肉', 'category': '肉类', 'calories': 165, 'protein': 31, 'carbs': 0, 'fat': 3.6, 'fiber': 0},
    {'id': 3, 'name': '西兰花', 'category': '蔬菜', 'calories': 34, 'protein': 2.8, 'carbs': 6.6, 'fat': 0.4,
     'fiber': 2.6},
    {'id': 4, 'name': '苹果', 'category': '水果', 'calories': 52, 'protein': 0.3, 'carbs': 13.8, 'fat': 0.2,
     'fiber': 2.4},
    {'id': 5, 'name': '鸡蛋', 'category': '蛋类', 'calories': 155, 'protein': 13, 'carbs': 1.1, 'fat': 11, 'fiber': 0},
    {'id': 6, 'name': '牛奶', 'category': '奶制品', 'calories': 54, 'protein': 3.4, 'carbs': 4.6, 'fat': 3.2,
     'fiber': 0},
    {'id': 7, 'name': '面包', 'category': '主食', 'calories': 265, 'protein': 9, 'carbs': 49, 'fat': 3.5, 'fiber': 2.7},
]

# 记录ID计数器
record_id_counter = 1

@app.route('/api/food-records', methods=['POST'])
def add_food_record():
    global record_id_counter
    try:
        data = request.get_json()
        print(f"📝 收到添加食物记录请求: {data}")

        # 创建新的食物记录
        new_record = {
            'id': record_id_counter,
            'food_name': data['food_name'],
            'category': data.get('category', '其他'),
            'meal_type': data['meal_type'],
            'record_date': data['record_date'],
            'record_time': data.get('record_time'),
            'calories': float(data['calories']),
            'protein': float(data.get('protein', 0)),
            'carbs': float(data.get('carbs', 0)),
            'fat': float(data.get('fat', 0)),
            'fiber': float(data.get('fiber', 0)),
            'weight': float(data.get('weight', 100)),
            'created_at': datetime.now().isoformat()
        }

        # 添加到模拟数据
        food_records.append(new_record)
        record_id_counter += 1

        print(f"✅ 记录添加成功，ID: {new_record['id']}")

        return jsonify({
            'message': '记录添加成功',
            'record': new_record,
            'record_id': new_record['id']
        }), 201

    except Exception as e:
        print(f"❌ 添加记录失败: {str(e)}")
        return jsonify({'error': '添加记录失败', 'details': str(e)}), 500


@app.route('/api/food-records/<date>', methods=['GET'])
def get_food_records(date):
    try:
        print(f"📅 获取 {date} 的食物记录")

        # 过滤指定日期的记录
        date_records = [record for record in food_records if record['record_date'] == date]

        meals = {
            'breakfast': [],
            'lunch': [],
            'dinner': [],
            'snack': []
        }

        total_calories = 0
        total_protein = 0
        total_carbs = 0
        total_fat = 0
        total_fiber = 0

        for record in date_records:
            # 添加到对应的餐次
            if record['meal_type'] in meals:
                meals[record['meal_type']].append(record)

            # 计算总营养
            total_calories += record['calories']
            total_protein += record['protein']
            total_carbs += record['carbs']
            total_fat += record['fat']
            total_fiber += record['fiber']

        print(f"✅ 找到 {len(date_records)} 条记录")

        return jsonify({
            'meals': meals,
            'summary': {
                'total_calories': total_calories,
                'total_protein': total_protein,
                'total_carbs': total_carbs,
                'total_fat': total_fat,
                'total_fiber': total_fiber,
                'target_calories': 2000,
                'target_protein': 60,
                'target_carbs': 300,
                'target_fat': 65,
                'target_fiber': 25
            }
        }), 200

    except Exception as e:
        print(f"❌ 获取记录失败: {e}")
        return jsonify({'error': '获取记录失败', 'details': str(e)}), 500


@app.route('/api/search-foods', methods=['GET'])
def search_foods():
    query = request.args.get('q', '')
    print(f"🔍 搜索食物: {query}")

    if not query:
        return jsonify([]), 200

    try:
        # 在食物数据库中搜索
        results = [food for food in food_database if query.lower() in food['name'].lower()]
        print(f"✅ 找到 {len(results)} 个结果")
        return jsonify(results), 200

    except Exception as e:
        print(f"❌ 搜索出错: {e}")
        return jsonify({'error': str(e)}), 500
# 在 app.py 中添加 DELETE 接口
@app.route('/api/food-records/<int:record_id>', methods=['DELETE'])
def delete_food_record(record_id):
    """删除食物记录"""
    global food_records
    try:
        print(f"🗑️ 收到删除记录请求，ID: {record_id}")
        print(f"📊 当前记录总数: {len(food_records)}")

        # 查找记录
        record_to_delete = None
        for record in food_records:
            if record['id'] == record_id:
                record_to_delete = record
                break

        if record_to_delete:
            # 删除记录
            food_records = [record for record in food_records if record['id'] != record_id]
            print(f"✅ 记录删除成功，ID: {record_id}")
            print(f"📊 删除后记录总数: {len(food_records)}")
            return jsonify({
                'message': '记录删除成功',
                'deleted_record': record_to_delete
            }), 200
        else:
            print(f"❌ 记录不存在，ID: {record_id}")
            return jsonify({'error': '记录不存在'}), 404

    except Exception as e:
        print(f"💥 删除记录异常: {e}")
        traceback.print_exc()
        return jsonify({'error': '删除记录失败', 'details': str(e)}), 500

# 健康检查接口
@app.route('/api/health', methods=['GET'])
def health_check():
    return jsonify({'status': 'healthy', 'message': '服务运行正常'}), 200


@app.route('/api/analysis', methods=['GET'])
def get_analysis():
    """获取营养分析数据"""
    try:
        period = request.args.get('period', 'week')
        date_str = request.args.get('date', datetime.now().strftime('%Y-%m-%d'))

        print(f"📊 获取分析数据 - 周期: {period}, 日期: {date_str}")

        # 解析日期
        target_date = datetime.strptime(date_str, '%Y-%m-%d')

        # 根据周期计算日期范围
        if period == 'day':
            start_date = target_date
            end_date = target_date
        elif period == 'week':
            start_date = target_date - timedelta(days=target_date.weekday())
            end_date = start_date + timedelta(days=6)
        elif period == 'month':
            start_date = target_date.replace(day=1)
            next_month = target_date.replace(day=28) + timedelta(days=4)
            end_date = next_month - timedelta(days=next_month.day)
        else:
            start_date = target_date - timedelta(days=target_date.weekday())
            end_date = start_date + timedelta(days=6)

        # 获取该时间段内的记录
        period_records = []
        for record in food_records:
            record_date = datetime.strptime(record['record_date'], '%Y-%m-%d')
            if start_date <= record_date <= end_date:
                period_records.append(record)

        # 计算总营养
        total_calories = sum(record['calories'] for record in period_records)
        total_protein = sum(record['protein'] for record in period_records)
        total_carbs = sum(record['carbs'] for record in period_records)
        total_fat = sum(record['fat'] for record in period_records)
        total_fiber = sum(record['fiber'] for record in period_records)

        # 目标值（根据周期调整）
        if period == 'day':
            target_calories = 2000
            target_protein = 60
            target_carbs = 300
            target_fat = 65
            target_fiber = 25
        elif period == 'week':
            target_calories = 2000 * 7
            target_protein = 60 * 7
            target_carbs = 300 * 7
            target_fat = 65 * 7
            target_fiber = 25 * 7
        elif period == 'month':
            target_calories = 2000 * 30
            target_protein = 60 * 30
            target_carbs = 300 * 30
            target_fat = 65 * 30
            target_fiber = 25 * 30

        # 生成趋势数据（最近7天）
        trend_data = []
        for i in range(7):
            day = target_date - timedelta(days=6 - i)
            day_str = day.strftime('%Y-%m-%d')

            # 计算该天的总热量
            day_calories = sum(
                record['calories'] for record in food_records
                if record['record_date'] == day_str
            )

            trend_data.append({
                'date': day_str,
                'calories': day_calories,
                'period': ['一', '二', '三', '四', '五', '六', '日'][i]
            })

        response_data = {
            'summary': {
                'total_calories': total_calories,
                'total_protein': total_protein,
                'total_carbs': total_carbs,
                'total_fat': total_fat,
                'total_fiber': total_fiber,
                'target_calories': target_calories,
                'target_protein': target_protein,
                'target_carbs': target_carbs,
                'target_fat': target_fat,
                'target_fiber': target_fiber
            },
            'trend_data': trend_data,
            'period': period,
            'date_range': {
                'start': start_date.strftime('%Y-%m-%d'),
                'end': end_date.strftime('%Y-%m-%d')
            }
        }

        print(f"✅ 分析数据生成成功 - 记录数: {len(period_records)}")
        return jsonify(response_data), 200

    except Exception as e:
        print(f"❌ 获取分析数据失败: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'error': '获取分析数据失败', 'details': str(e)}), 500

@app.route('/api/analyze-food', methods=['POST'])
def analyze_food():
    try:
        print("🎯 收到 /api/analyze-food 请求")
        data = request.get_json()

        image_base64 = data.get('image_base64', '')
        food_name = data.get('food_name', '').strip()

        print(f"🔍 详细解析数据:")
        print(f"   - 原始食物名称: '{food_name}'")
        print(f"   - 食物名称长度: {len(food_name)}")
        print(f"   - 食物名称是否为空: {food_name == ''}")
        print(f"   - 图片数据前缀: {image_base64[:50]}...")
        print(f"   - 图片数据长度: {len(image_base64)}")

        # 检查请求来源信息
        user_agent = request.headers.get('User-Agent', 'Unknown')
        print(f"   - 用户代理: {user_agent[:100]}...")

        # 检查是否是特殊标记的真实图片URI
        if image_base64.startswith('REAL_IMAGE_URI:'):
            file_uri = image_base64.replace('REAL_IMAGE_URI:', '')
            print(f"📁 收到真实图片URI: {file_uri}")

            # 如果用户没有输入食物名称，让后端自动识别
            if not food_name:
                print("🔄 用户未输入食物名称，使用自动识别")
                food_name = ""  # 明确设置为空
            else:
                print(f"🔄 用户输入了食物名称: '{food_name}'")

        # 调用食物分析器
        print("🔄 开始调用食物分析器...")
        analysis_result = food_analyzer.analyze_food_image(image_base64, food_name)

        if analysis_result:
            print(f"✅ 食物分析成功: {analysis_result['food_name']}")
            return jsonify(analysis_result), 200
        else:
            return jsonify({'error': '食物分析失败'}), 500

    except Exception as e:
        print(f"💥 食物分析接口异常: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'error': '服务器内部错误'}), 500

if __name__ == '__main__':
    print("🚀 SmartMeal 后端服务启动成功！")
    print(f"📱 讯飞星火 AppID: {Config.XUNFEI_APPID}")
    print(f"🔑 讯飞星火 API Password: {Config.XUNFEI_API_PASSWORD[:20]}...")
    print("📊 预加载食物数据库:", [food['name'] for food in food_database])
    print("🌐 服务地址: http://0.0.0.0:5000")
    print("📡 可用接口:")
    print("   POST /api/analyze-food - 分析食物")
    print("   POST /api/food-records - 添加食物记录")
    print("   GET  /api/food-records/<date> - 获取食物记录")
    print("   GET  /api/search-foods - 搜索食物")
    print("   GET  /api/health - 健康检查")
    app.run(host='0.0.0.0', port=5000, debug=True)


def db():
    return None